package com.async.designpatterns.create.prototype;

import java.io.*;

/**
 * Created by wenzhuo on 2018/1/1.
 */
public class Prototype implements Cloneable,Serializable {

    private static final long serialVersionUID = 1L;
    private String strValue;
    private int version;
    private SerializableObject obj;

    public Prototype(){
        obj = new SerializableObject();
    }

    @Override
    public Object clone() throws CloneNotSupportedException{
        Prototype prototype = (Prototype) super.clone();
        return prototype;
    }

    /**
     * 深拷贝
     */
    public Object deepClone() throws IOException, ClassNotFoundException {

        /**
         * 写入当前对象的二进制流
         */
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(this);

        /**
         * 读出二进制流产生的新对象
         */
        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bis);
        return ois.readObject();
    }

    public String getString() {
        return strValue;
    }

    public void setString(String string) {
        this.strValue = string;
    }

    public SerializableObject getObj() {
        return obj;
    }

    public void setObj(SerializableObject obj) {
        this.obj = obj;
    }

    static class SerializableObject implements Serializable{
        private static final Long serialVersionUID = 1L;
    }

    public int getVersion() {
        return version;
    }

    public void setVersion(int version) {
        this.version = version;
    }
}
